package com.antcom.antread.common.core.baseRest.controller;

import com.antcom.antread.common.core.baseRest.domain.GeneralSet;
import com.antcom.antread.common.core.utils.date.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;

/**
 * controller基类
 *
 * @Author 中国蚂蚁技术有限公司
 * @create 2020/11/29 9:40
 */
public class BaseRestController {

    @Resource
    protected HttpServletRequest request;

    @Resource
    protected HttpServletResponse response;

    /**
     * 普通操作成功
     *
     * @param data
     * @return
     */
    public GeneralSet success(Object data) {
        return new GeneralSet("success", "200", data);
    }

    /**
     * 成功
     * @return
     */
    public GeneralSet success() {
        return new GeneralSet("success", "200");
    }

    /**
     * 普通操作失败
     *
     * @return
     */
    public GeneralSet error() {
        return new GeneralSet("error", "500", null);
    }

    /**
     * 返回异常
     * @param e
     * @return
     */
    public GeneralSet error(String e){
        return new GeneralSet("error","500",e);
    }

    /**
     * 错误网关
     * @return
     */
    public GeneralSet badGateway(){
        return new GeneralSet("badGateway","500","[]");
    }

    /**
     * 获取参数
     * @param request
     * @return
     */
    public String getParam(HttpServletRequest request) {
        String paramStr = "";
        try {
            BufferedReader reader = null;
            request.setCharacterEncoding("UTF-8");
            reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            String line = null;
            StringBuilder buffer = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            paramStr = new String(buffer);

            if (StringUtils.isBlank(paramStr)) {
                paramStr = "{}";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paramStr;
    }

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     * @param binder 请求参数
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }
}
